package com.syh.jn.scm.service.impl.supplier.base;

import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.util.validator.ValidationUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.syh.core.ddd.infrastructure.repository.AggregateRepository;
import com.syh.core.ddd.service.AbstractServiceImpl;
import com.syh.jn.scm.domain.supplier.entity.base.Salesman;
import com.syh.jn.scm.domain.supplier.repository.base.SalesmanRepository;
import com.syh.jn.scm.dto.supplier.base.salesMan.SalesmanMto;
import com.syh.jn.scm.dto.supplier.base.salesMan.SalesmanSto;
import com.syh.jn.scm.dto.supplier.base.salesMan.SalesmanVo;
import com.syh.jn.scm.service.api.supplier.base.SalesmanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 销售代表管理
 */
@Service
@Transactional
public class SalesmanServiceImpl extends AbstractServiceImpl<SalesmanSto, SalesmanMto, SalesmanVo, Salesman, Long> implements SalesmanService {
  @Autowired
  private SalesmanRepository salesmanRepository;

  @Override
  protected AggregateRepository<Salesman, Long> getAggregateRepository() {
    return salesmanRepository;
  }

  /**
   * 保存对象
   *
   * @param sto
   * @return
   */
  @Override
  public Long save(SalesmanSto sto) {
    ExtAssert.notNull(sto, "保存对象为空");
    ValidationUtils.validate(sto);

    Salesman salesman = Salesman.createdSalesmanBySupply(sto);
    return salesmanRepository.add(salesman);
  }

  /**
   * 修改对象
   *
   * @param mto
   */
  @Override
  public void update(SalesmanMto mto) {
    ExtAssert.notNull(mto, "修改对象为空");
    ValidationUtils.validate(mto);

    //根据id获取销售代表信息并且判空
    Salesman salesman = this.getSalesmanById(mto.getId());

    salesman.modify(mto);
    salesmanRepository.update(salesman);
  }

  /**
   * 删除对象
   *
   * @param id
   */
  @Override
  public void delete(Long id) {
    //根据id获取销售代表信息并且判空
    Salesman salesman = this.getSalesmanById(id);

    salesman.destroy();
    salesmanRepository.removeById(id);
  }

  /**
   * 启用销售代表
   *
   * @param id
   */
  @Override
  public void enabled(Long id) {
    //根据id获取销售代表信息并且判空
    Salesman salesman = this.getSalesmanById(id);

    salesman.enabled();
    salesmanRepository.update(salesman);
  }

  /**
   * 停用销售代表
   *
   * @param id
   */
  @Override
  public void disabled(Long id) {
    //根据id获取销售代表信息并且判空
    Salesman salesman = this.getSalesmanById(id);

    salesman.disabled();
    salesmanRepository.update(salesman);
  }

  /**
   * 根据id获取销售代表信息并且判空
   *
   * @param id
   * @return
   */
  private Salesman getSalesmanById(Long id) {
    ExtAssert.notNull(id, "id为空");

    Salesman salesman = salesmanRepository.getById(id);
    ExtAssert.notNull(salesman, "对象为空");

    return salesman;
  }
}
